/*
 *  RYMOS
 *  Copyright (C) 2003 - 2012 Roberto Rodriguez 
 *
 *  This program is free software; you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation; either version 2 of the License, or 
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License 
 *  along with this program; if not, write to the Free Software 
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * contact me by e-mail<prfiredragon@gmail.com>
 * 
 *
 *  based on the SoftwareMultitasking tutorial from 
 *  http://code.google.com/p/onyxkernel/wiki/SoftwareMultitasking
 */

#include <system.h>
#include <task.h>
#include <drivers/timer.h>


int errors = 0;
int sched_active = 0;

int switch_pid(void)
{
	curr_pid = curr_pid + 1;
	if (curr_pid >= taskcount)
		curr_pid = 0;
	return curr_pid;
}

void SetSchedStatus(int status)
{
	sched_active = status;
}

int GetSchedStatus(void)
{
	return sched_active;
}

void SwitchTo(int p) {
	if (p < 2)
		return;
	curr_pid = p - 1;
}

uint32_t sched(uint32_t esp)
{
	timer_inc_tick();
	if (sched_active == 0)			// Is multitasking enabled?
		return esp;					// Scheduler turned off

	tasks[curr_pid].stack = esp;	// Save old esp
	switch_pid();					// Find next pid
		
	if (tasks[curr_pid].state)	// Is task still running?
	{
		tasks[curr_pid].spins++;
		return tasks[curr_pid].stack;
	}
	else							// No active tasks
	{
		return esp;					// Don't switch - no active tasks
	}
}
